<template>
	<!--  报工-->
	<div class="content">
		<div class="pageTableView" style="margin-top: 0">
			<div class="pageTableMenuView">
				<div class="pageTableTitle">
					<div>报工信息区</div>
				</div>
				<div class="pageTableButView">
					<el-button @click="goBack" :icon="ArrowLeft">返回</el-button>
					<el-button @click="handleAdd" type="primary" :icon="Calendar">报工</el-button>
				</div>
			</div>
			<!-- 表格 -->
			<el-table :data="paginatedData" height="calc(100vh - 185px)" row-key="id" :stripe="false"
								class="sort-el-table" header-cell-class-name="witheTableHeader">
				<el-table-column type="index" label="序号" width="80" align="center" />
				<el-table-column prop="reportWorkRecordNo" label="批次号" align="center" min-width="150" />
				<el-table-column prop="materialOutName" label="产出物料" align="center" min-width="220" />
				<el-table-column prop="reportTraceCode" label="追溯码" align="center" min-width="210" />
				<el-table-column prop="count" label="报工数量" align="center" width="150" />
				<el-table-column prop="status" label="物料状态" :formatter="statusType" align="center" />
				<el-table-column prop="isRevocation" label="物料去向" align="center">
					<template #default="scope">
						<div v-if="scope.row.isRevocation"> 撤销报工</div>
						<div v-else> 入库</div>
					</template>
				</el-table-column>
				<el-table-column prop="oneMaterialWeightCount" label="产出重量" align="center" />
				<el-table-column prop="createTime" label="报工时间" align="center" min-width="180" />
				<!--				<el-table-column prop="createUser" label="创建人" width="150" align="center" />-->
			</el-table>
		</div>
		<!-- 编辑/新建弹框 -->
		<el-dialog v-model="showCrud" title="报工" width="80%">
			<el-form :model="formData" label-width="100">
				<el-row :gutter="10">
					<el-col :span="8">
						<el-form-item label="工单号">{{ workInfo.workNo }}</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="产品名称">{{ workInfo.productName || '--' }}</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="模具名称" required>
							<el-select v-model="formData.toolRegisterId" clearable filterable placeholder="请选择模具名称"
												 style="width: 200px"
							>
								<el-option v-for="item in toolRegisterVOSList" :key="item.id" :label="item.registerName"
													 :value="item.id">
								</el-option>
							</el-select>
						</el-form-item>
						<!-- <el-form-item label="模具名称">{{ workInfo.registerName || '--' }}</el-form-item> -->
					</el-col>
					<el-col :span="8">
						<el-form-item label="总数">{{ workInfo.orderCount || '--' }}</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="已完成数量">{{ workInfo.finishCount || '--' }}</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item label="数量" required>
							<el-input-number v-model="formData.count" :step="1" :min="0" @input="countChange" />
							<!--							<el-button style="margin-left: 5px" @click="handleCount">计 算</el-button>-->
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="重量" required>
							<el-input-number v-model="formData.sumWeight" :step="0.001" :min="0" @input="sumWeightChange" />
							<!--							<el-butt
							on style="margin-left: 5px" @click="handleCount">计 算</el-button>-->
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="扣料数量">{{ deductedMaterialsQty || '--' }}</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="班组" required>
							<el-select v-model="formData.teamId" clearable filterable placeholder="请选择班组" style="width: 200px"
												 @change="basedataTeamListChange">
								<el-option v-for="item in basedataTeamList" :key="item.id" :label="item.name" :value="item.id">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item label="班次" required>
							<el-select v-model="formData.classId" clearable filterable placeholder="请选择班次" style="width: 200px"
												 @change="swingShiftChange">
								<el-option v-for="item in swingShiftList" :key="item.value" :label="item.text" :value="item.value">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item label="班次详情" required>
							<el-select v-model="formData.classJson" clearable filterable placeholder="请选择班次详情" style="width: 200px">
								<el-option v-for="item in classJsonList" :key="item.value" :label="item.text" :value="item.value">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item label="报工人" required>
							<el-select v-model="formData.operatorId" clearable filterable placeholder="请选择报工人" style="width: 200px">
								<el-option v-for="item in userList" :key="item.id " :label="item.userName" :value="item.id">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>


					<el-col :span="8">
						<el-form-item label="报工时间" required>
							<el-date-picker v-model="formData.reportTime" type="datetime" placeholder="选择报工时间"
															value-format="YYYY-MM-DD HH:mm:ss" />
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item label="产品状态" required>
							<el-radio-group v-model="formData.status">
								<el-radio value="0" size="small">不合格</el-radio>
								<el-radio value="1" size="small">合格</el-radio>
								<el-radio value="2" size="small">报废</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>


				</el-row>
				<!--				<el-row :gutter="10" style="padding: 10px">-->
				<!--					<el-table :data="formData.materialList" style="width:100% " height="300px">-->
				<!--						<el-table-column label="序号" type="index" align="center" width="80" />-->
				<!--						<el-table-column prop="materialName" label="物料名称" align="center" />-->
				<!--						<el-table-column prop="batchNo" label="批次号" align="center">-->
				<!--							<template #default="scope">-->
				<!--								<el-select v-model="scope.row.batchNo" placeholder="请选择批次号"-->
				<!--									@change="batchNoChange(scope.$index)">-->
				<!--									<el-option v-for="item in scope.row.batchNoList" :key="item" :label="item"-->
				<!--										:value="item" />-->
				<!--								</el-select>-->
				<!--							</template>-->
				<!--						</el-table-column>-->
				<!--						<el-table-column prop="frontTraceabilityCode" label="追溯码" align="center" />-->
				<!--						<el-table-column prop="otherNum" label="剩余数量" align="center">-->
				<!--							<template #default="scope">-->
				<!--								<div>{{ scope.row.otherNum || 0 }}</div>-->
				<!--							</template>-->
				<!--						</el-table-column>-->
				<!--						<el-table-column prop="sumWeight" label="产出重量" align="center">-->
				<!--							<template #default="scope">-->
				<!--								<div>{{ scope.row.sumWeight || 0 }}</div>-->
				<!--							</template>-->
				<!--						</el-table-column>-->
				<!--						<el-table-column prop="materialName" label="扣除数量" align="center">-->
				<!--							<template #default="scope">-->
				<!--								<el-input-number v-model="scope.row.count" />-->
				<!--							</template>-->
				<!--						</el-table-column>-->
				<!--					</el-table>-->
				<!--				</el-row>-->
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="showCrud = false">取消</el-button>
					<el-button type="primary" @click="handleSave">确定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<script lang="ts" setup>
import { ref, computed, watch, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axiosInstance from '@/utils/http/api';
import {
	Delete, Edit, Tickets, DocumentChecked, ArrowLeft
	, Search, Share, Upload, Refresh, Plus, DocumentCopy, Files, Rank, Calendar
} from '@element-plus/icons-vue';
import type { FormInstance, FormRules } from 'element-plus';
import { equipmentAll } from '@/api/scheduling/dispatchManagement';

const paginatedData = ref([]);//列表数据
const searchParam = ref({});
const formData = ref({});
const outMaterialOneMaterialWeight = ref(null);

const workInfo = ref({});
const statusType = (e) => {
	const list = [{
		label: '不合格',
		value: '0'
	}, {
		label: '合格',
		value: '1'
	}, {
		label: '报废',
		value: '2'
	}];
	const type = list.find(type => type.value == e.status);
	return type ? type.label : '';
};

// 班组 班次 班次详情 报工人
const basedataTeamList = ref([]);
const swingShiftList = ref([]);
const classJsonList = ref([]);
const classJson = ref({});
const userList = ref([]);
const oldSwingShiftList = ref([]);
const toolRegisterVOSList = ref([]);
const basedataTeamListChange = (e) => {
	const list = basedataTeamList.value.find(item => item.id == e);
	userList.value = list.teamUserDTOS;
	const tokenUserId = localStorage.getItem('tokenUserId');
	if (userList.value.some(user => user.id === tokenUserId)) {
		formData.value.operatorId = tokenUserId;
	}
};

const swingShiftChange = (e) => {
	classJson.value = null;
	classJsonList.value = swingShiftList.value.find(item => item.value == e).shiftJson;

};

const countChange = (e) => {
	if (outMaterialOneMaterialWeight.value) {
		formData.value.sumWeight = (e * outMaterialOneMaterialWeight.value).toFixed(3);
	}
	if (workInfo.value.inMasterNumPutCompare) {
		deductedMaterialsQty.value = (formData.value.count * workInfo.value.inMasterNumPutCompare).toFixed(3);
	}
};

const sumWeightChange = (e) => {
	if (outMaterialOneMaterialWeight.value) {
		formData.value.count = (e / outMaterialOneMaterialWeight.value).toFixed(0);

		if (workInfo.value.inMasterNumPutCompare) {
			deductedMaterialsQty.value = (formData.value.count * workInfo.value.inMasterNumPutCompare).toFixed(3);
		}

	} else {
		// ElMessage.error('未配置产品重量');
		return false;
	}
};


const getOption = () => {
	axiosInstance.post('/api/workOrder/queryByWorkId', {
		id: route.query.id
	})
		.then(res => {
			if (res.code !== 200) {
				ElMessage.error(res.message);
				return false;
			}
			workInfo.value = res.data;
			outMaterialOneMaterialWeight.value = res.data?.outMaterialOneMaterialWeight;
			paginatedData.value = res.data.reportWorkRecords;
			toolRegisterVOSList.value = res.data.toolRegisterVOS;

		});

	axiosInstance.post('/api/basedataTeam/getPage', {
		'current': 1,
		'pageSize': 99999
	})
		.then(res => {
			if (res.code !== 200) {
				ElMessage.error(res.message);
				return false;
			}
			basedataTeamList.value = res.data.records;
		});

	axiosInstance.post('/api/swingShift/getPage', {
		'current': 1,
		'pageSize': 99999
	})
		.then(res => {
			if (res.code !== 200) {
				ElMessage.error(res.message);
				return false;
			}

			// 创建一个映射关系
			const shiftNameMap = {
				'0': '早班',
				'1': '中班',
				'2': '晚班'
			};

			oldSwingShiftList.value = res.data.records;
			swingShiftList.value = res.data.records.map((item, index) => {
				// 解析shiftJson
				let shiftData = JSON.parse(item.shiftJson);

				// 遍历shiftData中的每个项目，并添加name和value属性
				shiftData.forEach((shiftItem, shiftIndex) => {
					shiftItem.name = shiftNameMap[shiftItem.shiftName] || '未知班次';
					shiftItem.text = shiftItem.name + '：' + shiftItem.startTime + '-' + shiftItem.endTime;
					// 添加value属性，这里使用shiftIndex作为唯一索引
					shiftItem.value = shiftIndex;
				});

				// 返回新的对象
				return {
					text: item.name,
					value: item.id,
					shiftJson: shiftData
				};
			});


		});
};

const deductedMaterialsQty = ref(null);

const showCrud = ref(false); // 编辑/新建弹框

import { useRouter, useRoute } from 'vue-router';

const route = useRoute();
const router = useRouter();

import moment from 'moment';
// 新建记录
const handleAdd = () => {
	// const id =  localStorage.getItem('tokenUserId')
	formData.value = {
		status: '1',
		reportTime: moment().format('YYYY-MM-DD HH:mm:ss')
	};
	axiosInstance.post('/api/reportWorkRecord/getToolRegisterCode', {
		'workOrderId': route.query.id
	}).then(res => {
		if (res.data) {
			formData.value.toolRegisterId = toolRegisterVOSList.value.find(item => item.toolRegisterCode == res.data).id;
		}
		// formData.value.materialList = res.data;
	});
	showCrud.value = true;
};

const handleCount = () => {
	if (!formData.value.count || formData.value.count == 0) {
		ElMessage.warning('请填写数量');
		return false;
	}

	const param = [];


	param.push({
		workOrderId: route.query.id,
		count: formData.value.count,
		registerNo: workInfo.value.registerNo
	});


	axiosInstance.post('/api/reportWorkRecord/queryResidueCount', param)
		.then(res => {
			if (res.code !== 200) {
				ElMessage.error(res.message);
				return false;
			}
			// let showTitle = false
			for (const item of formData.value.materialList) {
				for (const items of res.data) {
					if (item.materialId == items.materialId) {
						item.count = items.putMaterialCount;
						item.sumWeight = items.sumWeight;
						// if (item.otherNum < item.count) {
						//   showTitle = true
						// }
					}
				}
			}

			// if (showTitle) {
			//   ElMessageBox.alert('列表中扣除数量大于剩余数量', '提示', {
			//     // if you want to disable its autofocus
			//     // autofocus: false,
			//     confirmButtonText: '知道了'
			//   })
			// }
			// ElMessage.success('报工成功!');
			// showCrud.value = false
			// getList()
		});
};

const batchNoChange = (e) => {
	const info = JSON.parse(JSON.stringify(formData.value.materialList[e]));
	const param = {
		materialId: info.materialId,
		batchNo: info.batchNo,
		current: 1,
		pageSize: 999999,
		workId: workInfo.value.id
	};
	axiosInstance.post('/api/warehouseStorageMaterial/pageByPojo', param).then(res => {
		if (res.code != 200) {
			ElMessage.error(res.message);
			return false;
		}

		const loop = [];
		for (const item of res.data.records) {
			if (item.materialStatus == 3) {
				loop.push(item);
			}
		}
		// batchNoList.value = loop
		if (loop.length && loop.length > 0) {
			info.otherNum = loop[0].count;
			info.frontTraceabilityCode = loop[0].traceabilityCode;
		}

		formData.value.materialList[e] = info;
	});
};


const goBack = () => {
	router.go(-1);
};


// 保存记录
const handleSave = async () => {
	// const list = JSON.parse(JSON.stringify(formData.value.materialList));
	// for (const item of list) {
	// 	item.outPutCount = item.count;
	// }
	// for (const item of list) {
	// 	param.push({
	// 		...item,
	// 		...{
	// 			workOrderId: route.query.id,
	// 			count: formData.value.count,
	// 			registerNo: workInfo.value.registerNo
	// 		}
	// 	})
	// 	;
	// }

	// if (!formData.value.count || formData.value.count == 0) {
	//   ElMessage.warning('请填写数量');
	//   return false;
	// }
	// if (!formData.value.sumWeight || formData.value.sumWeight == 0) {
	//   ElMessage.warning('请填写重量');
	//   return false;
	// }
	// if (!formData.value.teamId) {
	//   ElMessage.warning('请选择班组');
	//   return false;
	// }
	// if (!formData.value.classId) {
	//   ElMessage.warning('请选择班次');
	//   return false;
	// }
	// if (!formData.value.classJson && formData.value.classJson != 0) {
	//   ElMessage.warning('请选择班次详情');
	//   return false;
	// }
	// if (!formData.value.operatorId) {
	//   ElMessage.warning('请选择报工人');
	//   return false;
	// }
	//
	// if (formData.value.status == null || formData.value.status == '') {
	//   ElMessage.warning('请选择产品状态');
	//   return false;
	// }

	const param = JSON.parse(JSON.stringify(formData.value));

	// if (formData.value.materialList && formData.value.materialList.langeh == 0) {
	// 	ElMessage.warning('没有物料信息，不能报工');
	// 	return false;
	// }
	// for (const item of formData.value.materialList) {
	// 	if (!item.batchNo) {
	// 		ElMessage.warning('请选择批次号');
	// 		return false;
	// 	}
	// 	if (!item.count || item.count == 0) {
	// 		ElMessage.warning('请填写扣除数量');
	// 		return false;
	// 	}
	// }
	const classList = JSON.parse(oldSwingShiftList.value.find(item => item.id = formData.value.classId).shiftJson);
	console.log(classList, typeof classList);
	let classJson = classList[formData.value.classJson];
	// if(!workInfo.value.isThrowOrWP){
	//   param.isWorkorderOrProcedure = workInfo.value.isWorkorderOrProcedure
	// }
	param.workOrderId = route.query.id;
	param.classJson = JSON.stringify(classJson);
	param.materialId = pageData.value.materialId;
	console.log(param);


	axiosInstance.post('/api/reportWorkRecord/saveReportData', param)
		.then((res) => {
			if (res.code !== 200) {
				ElMessage.error(res.message);
				return false;
			}
			showCrud.value = false;
			getList();
		});
};

const pageData = ref({});
// 获取列表
const getList = async () => {
	axiosInstance.post('/api/workOrder/queryByWorkId', {
		id: route.query.id
	})
		.then(res => {
			if (res.code !== 200) {
				ElMessage.error(res.message);
				return false;
			}
			pageData.value = res.data;
			paginatedData.value = res.data.reportWorkRecords;
			// pageTotal.value = res.data.total;
		});
};

onMounted(() => {
	// getList();
	getOption();
});
</script>
<style scoped lang="scss">
.pageTableButView {
	display: flex;
	/*gap: 10px;*/
	height: 40px;
}


</style>
